﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dln.Common.WxPayAPI;
using Dln.Model;
using Dln.Common.Helper;
using Dln.Common;
using System.Xml;

public partial class example_ResultNotifyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ResultNotify resultNotify = new ResultNotify(this);

        resultNotify.ProcessNotify();
    }
}

/// <summary>
/// 支付结果通知回调处理类
/// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
/// </summary>
public class ResultNotify : Notify
{
    public ResultNotify(Page page)
        : base(page)
    {
    }

    public override void ProcessNotify()
    {
        WxPayData notifyData = GetNotifyData();
        string return_code = "SUCCESS";
        string return_msg = "";
        string url = CommonHelper.GetAppSettings("DlnService1");

        Log.Debug(this.GetType().ToString(), "Line28,code=" + "支付回调完成");
        //检查支付结果中transaction_id是否存在
        if (!notifyData.IsSet("transaction_id"))
        {
            //若transaction_id不存在，则立即返回结果给微信支付后台
            WxPayData res = new WxPayData();
            res.SetValue("return_code", "FAIL");
            res.SetValue("return_msg", "支付结果中微信订单号不存在");
            Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
            page.Response.Write(res.ToXml());
            page.Response.End();
        }

        var transaction_id = notifyData.GetValue("transaction_id").ToString();

        //查询订单，判断订单真实性
        if (!QueryOrder(transaction_id))
        {
            //若订单查询失败，则立即返回结果给微信支付后台
            WxPayData res = new WxPayData();
            res.SetValue("return_code", "FAIL");
            res.SetValue("return_msg", "订单查询失败");
            Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
            page.Response.Write(res.ToXml());
            page.Response.End();
        }
        //查询订单成功
        else
        {
            var orderno = notifyData.GetValue("out_trade_no").ToString();
            var total_fee = notifyData.GetValue("cash_fee").ToString();
            try
            {
                if (!string.IsNullOrWhiteSpace(orderno))
                {
                    Log.Info(this.GetType().ToString(), "orderno : " + orderno);
                    var order = SqlHelper.Context.From<BuildCardRecord>().Where(d => d.PreOrderNo == orderno && d.DelStatus == 0).ToFirst();
                    if (order != null)
                    {
                        order.PayNo = transaction_id;
                        order.PayMoney = Convert.ToDecimal(total_fee) / 100;
                        order.PayTime = DateTime.Now;
                        order.Remark = notifyData.ToJson();
                        var count = SqlHelper.Context.Update<BuildCardRecord>(order);

                        Log.Info(this.GetType().ToString(), "微信支付通知: " + notifyData.ToJson());

                        if (count > 0)
                        {
                            if (orderno.Substring(0, 2).ToUpper() == "EH")
                            {
                                //支付医嘱
                                Dln.Common.ServiceReference1.Service1SoapClient client2 = new Dln.Common.ServiceReference1.Service1SoapClient();
                                object result = client2.SetOrdInftollTwo(order.PatiName, order.PatiIdCard, Convert.ToDecimal(order.PayMoney), order.PreOrderNo,"微信","微信","");
                                if (result != null)
                                {
                                    var isExistReturn = result.ToString().Contains("return");
                                    if (isExistReturn)
                                    {
                                        string xml = "<outContent>" + result.ToString() + "</outContent>";
                                        XmlDocument x = new XmlDocument();
                                        x.LoadXml(xml);
                                        XmlNodeList nodeList = x.SelectNodes("outContent");
                                        var flag = nodeList[0].ChildNodes[0].InnerText;
                                        if (flag == "0")
                                        {
                                            return_code = "FAIL";
                                            return_msg = "支付回调：" + nodeList[0].ChildNodes[1].InnerText;
                                        }
                                        else
                                        {
                                            //保存支付记录HIS

                                        }
                                    }
                                    else
                                    {
                                        return_code = "FAIL";
                                        return_msg = "支付回调：门诊处方支付失败";
                                    }
                                }
                            }
                            else
                            {
                                //建卡
                                object[] arge = new object[3];
                                arge[0] = order.PatiName;
                                arge[1] = order.PatiIdCard;
                                arge[2] = order.PatiPhone;
                                //object getCurrInHospNum = WebServiceHelper.InvokeWebService(url, "CreadCard", arge);
                                Dln.Common.ServiceReference1.Service1SoapClient client2 = new Dln.Common.ServiceReference1.Service1SoapClient();
                                object getCurrInHospNum = client2.CreadCard(order.PatiName, order.PatiIdCard, order.PatiPhone);
                                if (getCurrInHospNum != null)
                                {
                                    var isExistReturn = getCurrInHospNum.ToString().Contains("return");
                                    if (isExistReturn)
                                    {
                                        string xml = "<outContent>" + getCurrInHospNum.ToString() + "</outContent>";
                                        XmlDocument x = new XmlDocument();
                                        x.LoadXml(xml);
                                        XmlNodeList nodeList = x.SelectNodes("outContent");
                                        var flag = nodeList[0].ChildNodes[0].InnerText;
                                        if (flag == "0")
                                        {
                                            return_code = "FAIL";
                                            return_msg = "支付回调：" + nodeList[0].ChildNodes[1].InnerText;
                                        }
                                        else
                                        {
                                            order.HISCardID = nodeList[0].ChildNodes[1].InnerText;
                                            SqlHelper.Context.Update<BuildCardRecord>(order); //更新就诊卡号
                                        }
                                    }
                                    else
                                    {
                                        return_code = "FAIL";
                                        return_msg = "支付回调：建卡失败1";
                                    }
                                }
                                else
                                {
                                    return_code = "FAIL";
                                    return_msg = "支付回调：建卡失败2";
                                }
                            }
                        }
                        else
                        {
                            return_code = "FAIL";
                            return_msg = "支付回调：订单号：" + orderno + "更新支付信息失败";
                        }
                    }
                    else
                    {
                        return_code = "FAIL";
                        return_msg = "支付回调：订单号：" + orderno + "未查到该订单记录";
                    }
                }
                else
                {
                    return_code = "FAIL";
                    return_msg = "支付回调：返回订单号为空";
                }
            }
            catch (Exception ex)
            {
                return_msg = ex.Message;
                Log.Info(this.GetType().ToString(), "微信支付通知异常: " + ex.ToString());
            }
            finally
            {
                if (return_msg == "")
                {
                    return_msg = "OK";
                    Log.Info(this.GetType().ToString(), "支付通知处理成功:" + orderno);
                }
                else
                {
                    Log.Error(this.GetType().ToString(), "支付通知处理失败:" + orderno + return_msg);
                }
                WxPayData res = new WxPayData();
                res.SetValue("return_code", return_code);
                res.SetValue("return_msg", return_msg);
                page.Response.Write(res.ToXml());
                page.Response.End();
            }

        }

    }

    //查询订单
    private bool QueryOrder(string transaction_id)
    {
        WxPayData req = new WxPayData();
        req.SetValue("transaction_id", transaction_id);
        WxPayData res = WxPayApi.OrderQuery(req);
        return res.GetValue("return_code").ToString() == "SUCCESS" && res.GetValue("result_code").ToString() == "SUCCESS";
    }
}
